from flask import Blueprint, render_template_string

from importlib import import_module
from sqlalchemy import inspect
from pathlib import Path
import ast

from app.middleware import debug_only
from config import GlobalContextData

app = Blueprint('database', __name__, url_prefix='/database')

if GlobalContextData.Debug:
    print(' * Startup database webui: http://localhost:5000/database/')

# Function to extract class names from a Python file
def get_classes_from_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        node = ast.parse(file.read())
        return [n.name for n in ast.walk(node) if isinstance(n, ast.ClassDef)]

database_struct = {}
database_model_cache = {}
objects = [x for x in Path('db').glob('*.py') if '__' not in x.name]
for _object in objects:
    class_names = get_classes_from_file(_object)
    database_struct[_object.stem] = class_names

db_dir = Path.cwd() / 'static' / 'db'

# http://localhost:5000/database/
@app.route('/')
@debug_only
def index():
    return render_template_string((db_dir / 'index.html').read_text(encoding='utf-8'), database_struct=database_struct)

@app.route('/<model_name>/<class_name>')
@debug_only
def table_detail(model_name: str, class_name: str):
    module_name = f"db.{model_name}"
    module = import_module(module_name)
    db = getattr(module, class_name, None)

    table_name = db.__tablename__

    inspector = inspect(db)
    columns = inspector.columns
    columns = [{'name': column.name, 'type': str(column.type), 'nullable': column.nullable} for column in columns]


    return render_template_string((db_dir / 'table_detail.html').read_text(encoding='utf-8'),
                                  table_name=table_name,
                                  columns=columns)
